//
//  ShowChildControllerable.swift
//  Social
//
//  Created by 李响 on 2019/3/14.
//  Copyright © 2019 shengsheng. All rights reserved.
//

import Foundation
import UIKit

protocol ShowChildControllerable {
    
    /// 显示
    ///
    /// - Parameters:
    ///   - parent: 父控制器
    ///   - animated: 是否动画
    func show(in parent: UIViewController, animated: Bool, completion: @escaping () -> Void)
    
    /// 隐藏
    ///
    /// - Parameter animated: 是否动画
    func hide(_ animated: Bool, completion: @escaping () -> Void)
}

extension ShowChildControllerable where Self: UIViewController {
    
    func show(in parent: UIViewController, animated: Bool, completion: @escaping (() -> Void) = {}) {
        parent.addChild(self)
        parent.view.addSubview(view)
        didMove(toParent: parent)
        view.fillToSuperview()
        
        view.alpha = 0.0
        CATransaction.begin()
        CATransaction.setCompletionBlock {
            completion()
        }
        UIView.beginAnimations("", context: nil)
        UIView.setAnimationDuration(animated ? 0.2 : 0.0)
        view.alpha = 1.0
        UIView.commitAnimations()
        CATransaction.commit()
    }
    
    func hide(_ animated: Bool, completion: @escaping (() -> Void) = {}) {
        view.endEditing(true)
        view.alpha = 1.0
        CATransaction.begin()
        CATransaction.setCompletionBlock {
            self.willMove(toParent: nil)
            self.view.removeFromSuperview()
            self.removeFromParent()
            completion()
        }
        UIView.beginAnimations("", context: nil)
        UIView.setAnimationDuration(animated ? 0.2 : 0.0)
        view.alpha = 0.0
        UIView.commitAnimations()
        CATransaction.commit()
    }
}
